#pragma once

#include <EEPROM.h>
#include <WiFi.h>
#include <DNSServer.h>
#include <WebServer.h>

const char *AP_Name = "ESP32_AP";
char STA_ssid[32] = {0};
char STA_password[32] = {0};
byte ssid_addr = 10;  // EEPROM的地址10
byte pwd_addr = 30;  // EEPROM的地址30

const char *page_html = "\
<!DOCTYPE html>\r\n\
<html lang='en'>\r\n\
<head>\r\n\
  <meta charset='UTF-8'>\r\n\
  <meta name='viewport' content='width=device-width, initial-scale=1.0'>\r\n\
  <title>Document</title>\r\n\
</head>\r\n\
<body>\r\n\
  <form name='input' action='/' method='POST'>\r\n\
        wifi名称: <br>\r\n\
        <input type='text' name='ssid'><br>\r\n\
        wifi密码:<br>\r\n\
        <input type='text' name='password'><br>\r\n\
        <input type='submit' value='保存'>\r\n\
    </form>\r\n\
</body>\r\n\
</html>\r\n\
";

const byte DNS_PORT = 53;       // DNS端口号
IPAddress apIP(192, 168, 4, 1); // ESP32-AP-IP地址
DNSServer dnsServer;            // 创建dnsServer实例
WebServer server(80);           // 创建WebServer

void ConnectWifi();
/*访问主页回调函数*/
void handleRoot()
{
    server.send(200, "text/html", page_html);
}

/*Post回调函数*/
void handleRootPost()
{
    Serial.println("handleRootPost");
    if (server.hasArg("ssid"))
    {
        Serial.print("got ssid:");
        strcpy(STA_ssid, server.arg("ssid").c_str()); // 将账号参数拷贝到sta_ssid中
        EEPROM.put(ssid_addr, STA_ssid);
        EEPROM.commit();

        Serial.println(EEPROM.get(ssid_addr, STA_ssid));
    }
    else
    {
        Serial.println("error, not found ssid");
        server.send(200, "text/html", "<meta charset='UTF-8'>error, not found ssid"); // 返回错误页面
        return;
    }

    if (server.hasArg("password"))
    {
        Serial.print("got password:");
        strcpy(STA_password, server.arg("password").c_str());
        EEPROM.put(pwd_addr, STA_password);
        EEPROM.commit();
        Serial.println(EEPROM.get(pwd_addr, STA_password));
    }
    else
    {
        Serial.println("error, not found password");
        server.send(200, "text/html", "<meta charset='UTF-8'>error, not found password");
        return;
    }

    server.send(200, "text/html", "<meta charset='UTF-8'>保存成功"); // 返回保存成功页面
    delay(1000);

    ConnectWifi(); // 连接wifi
}

/*初始化AP模式*/
void initSoftAP(void)
{
    WiFi.mode(WIFI_AP);
    WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
    if (WiFi.softAP(AP_Name))
    {
        Serial.println("SoftAP is right");
    }
}

/*初始化WebServer*/
void initWebServer(void)
{
    server.on("/", HTTP_GET, handleRoot);      // 设置主页回调函数
    server.onNotFound(handleRoot);             // 设置无法响应的http请求的回调函数
    server.on("/", HTTP_POST, handleRootPost); // 设置Post请求回调函数
    server.begin();                            // 启动WebServer
    Serial.println("WebServer started!");
}

/*初始化DNS服务器*/
void initDNS(void)
{
    if (dnsServer.start(DNS_PORT, "*", apIP))
    { // 判断将所有地址映射到ESP32的ip上是否成功
        Serial.println("start dnsserver success.");
    }
    else
        Serial.println("start dnsserver failed.");
}

void ConnectWifi()
{
    WiFi.mode(WIFI_STA);       // 切换为STA模式
    WiFi.setAutoConnect(true); // 设置自动连接
    WiFi.begin(EEPROM.get(ssid_addr, STA_ssid), EEPROM.get(pwd_addr, STA_password));
    Serial.println("");
    Serial.print("Connect to wifi");
    int count = 0;
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(800);
        count++;
        if (count > 10)
        {                    // 如果8秒内没有连上，就开启Web配网 可适当调整这个时间
            initSoftAP();    // 切换为AP模式
            initWebServer(); // 获取Web输入信息
            initDNS();
            break; // 跳出 防止无限初始化
        }
        Serial.print(".");
    }
    Serial.println("");
    if (WiFi.status() == WL_CONNECTED)
    {
        Serial.println("WIFI Connected!");
        Serial.print("IP address: ");
        Serial.println(WiFi.localIP());
        server.stop();
    }
}